import { useMemo, useState } from 'react'
import styled from 'styled-components'
import EventBus from './common/eventbus'
import Tiles from './tiles'
import { EventType, Menu, State } from './tiles/context'

export function App() {
  const [state, setState] = useState<State | null>(null)
  const [menu, setMenu] = useState<Menu | null>(null)
  const eventbus = useMemo(() => new EventBus<EventType>()
    .on('tilesStatusChanged', setState)
    .on('tilesRightClick', setMenu)
    , [])

  return <>
    <Container>
      <StyledTiles
        id='tiles'
        gridsize={32}
        eventbus={eventbus}
      />
    </Container>
    <StatusBar>{stateDescription(state)}</StatusBar>
    <RightClickMenu menu={menu} setMenu={setMenu} />
  </>
}

function stateDescription(state: State | null) {
  if (state == null) return ''
  const { scale, cursor: { x, y } } = state
  return `${(scale * 100).toFixed(0)}% ${x},${y}`
}

function RightClickMenu(props: { menu: Menu | null, setMenu: (menu: Menu | null) => void }) {
  const { menu, setMenu } = props

  if (menu == null) return

  return (
    <MenuMask
      onClick={e => {
        e.stopPropagation()
        setMenu(null)
      }}
      onContextMenu={e => {
        e.preventDefault()
        setMenu(null)
      }}
    >
      <MenuBox $clientX={menu?.clientX ?? 0} $clientY={menu?.clientY ?? 0} >
        {Array.from(menu?.items.entries() || []).map(([key, callback]) => (
          <MenuItem
            key={key}
            onClick={e => {
              e.stopPropagation()
              setMenu(null)
              callback()
            }}>
            {key}
          </MenuItem>
        ))}
      </MenuBox>
    </MenuMask>
  )
}

const Container = styled.div`
	height: 100%;
  display: flex;
  flex-direction: column;
`

const StatusBar = styled.div`
    position: fixed;
    bottom: 5px;
    left: 5px;
    color: white;
		font-size: .75rem;
`

const MenuBox = styled.div<{ $clientX: number, $clientY: number }>`
    position: absolute;
    background-color: #3c8383;
    padding: 0.5rem 5px;
    border-radius: 0.5rem;
    left: ${props => props.$clientX}px;
    top: ${props => props.$clientY}px;
`

const MenuMask = styled.div`
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
`

const MenuItem = styled.div`
    cursor: pointer;
		color: white;
		padding: 5px 1rem;
		border-radius: 5px;
		text-align: left;
		text-transform: capitalize;
		font-size: 0.75rem;
    &:hover {
        background-color: rgba(255, 255, 255, 0.1);
    }
`
const StyledTiles = styled(Tiles)`
    width: 100%;
    background-color: darkslategray;
    flex: 3;
    border-top: 1px solid white;
    overflow: hidden;
`